package com.innjia.sys.controller;

import com.innjia.base.utils.Result;
import com.innjia.base.utils.ValidatorUtils;
import com.innjia.sys.entity.FileEntity;
import com.innjia.sys.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <br>
 * 2017-11-15
 *
 * @author zhouxianglh@gmail.com
 */
@RestController
@RequestMapping("/file")
public class FileController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    @RequestMapping(value = "/image/house/{auth}", method = RequestMethod.POST)
    public Result houseImageUpload(@PathVariable(required = false, value = "") String auth,
                                   @RequestBody FileEntity fileEntity){
        if(ValidatorUtils.isEmpty(fileEntity.getPath())){
            return Result.error("文件不能为空");
        }
        if(ValidatorUtils.isEmpty(fileEntity.getType())){
            return Result.error("文件类型不能为空");
        }

        String fileLevelPath = File.separator + "images" + File.separator + "house";
        String fileId;
        if(ValidatorUtils.isEquals("auth", auth)){
            fileLevelPath = File.separator + "images" + File.separator + "house" + File.separator + "auth";
        }

        fileId = fileService.saveBase64File(null,
                fileEntity.getPath(), fileLevelPath, fileEntity.getType());

        Map<String, Object> data = new HashMap<>();
        data.put("imageUrl", "/file/getfile/" + fileId);

        return Result.ok(data);
    }

    /**
     * 删除文件
     *
     * @param fileId
     */
    public void deleteFile(String fileId) {
        fileService.deleteFile(fileId);
    }

    @RequestMapping("/getfile/{fileId}/{fileName}")
    public void getFileWeb(@PathVariable String fileId, @PathVariable(required = false, value = "") String fileName, HttpServletResponse response) throws IOException {
        byte[] data = getFile(fileId);
        response.reset();
        response.setContentType("application/force-download");// 设置强制下载不打开
        if (StringUtils.isBlank(fileName)) {
            fileName = fileId;
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
    }
    @RequestMapping("/getfile/{fileId}")
    public void getFile(@PathVariable String fileId, HttpServletResponse response) throws IOException {
        byte[] data = getFile(fileId);
        response.reset();
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileId + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 获取文件
     *
     * @param fileId
     * @return
     */
    public byte[] getFile(@PathVariable String fileId) {
        return fileService.getFile(fileId);
    }

    /**
     * 保存文件
     *
     * @param limitDate
     *         有效期
     * @param filePath
     * @return
     * @throws IOException
     */
    public String saveFile(Date limitDate, String filePath) throws IOException {
        return saveFile(limitDate, new File(filePath));
    }

    /**
     * 保存文件
     *
     * @param limitDate
     *         有效期
     * @param file
     * @return
     * @throws IOException
     */
    public String saveFile(Date limitDate, File file) {
        try (FileInputStream inputStream = new FileInputStream(file)) {
            return saveFile(limitDate, new FileInputStream(file));
        } catch (IOException e) {
            LOGGER.error("", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存文件
     *
     * @param limitDate
     *         有效期
     * @param inputStream
     *         inputStream调用后并不会关闭,需要调用者手动关闭
     * @return
     */
    public String saveFile(Date limitDate, InputStream inputStream) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(inputStream.available())) {
            byte[] data = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, length);
            }
            return saveFile(limitDate, outputStream.toByteArray());
        } catch (Exception e) {
            LOGGER.error("", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存文件
     *
     * @param limitDate
     *         有效期
     * @param data
     * @return
     */
    public String saveFile(Date limitDate, byte[] data) {
        return fileService.saveFile(limitDate, data, null);
    }
}
